﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using FantastPlatform.Core.Extensions;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Script.Serialization;
using System.Globalization;
using FantastPlatform.Framework.IModel;
using Newtonsoft.Json.Converters;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using FantastPlatform.Framework.Model;


namespace FantastPlatform.Decision.UI
{
    public class BasePage : System.Web.UI.Page
    {
        protected TEntity JsonToEntity<TEntity>(string json)
        {
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(TEntity));
            json = RepairString(json);
            var mStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
            TEntity entity = (TEntity)obj.ReadObject(mStream);
            return entity;
        }

        protected void ReturnObj(Object obj)
        {
            if (obj == null)
            {
                return;
            }
            string jsonStr = JsonConvert.SerializeObject(obj);

            jsonStr = "{ 'success': 'true', 'data': " + jsonStr + "}";

            Response.Write(jsonStr);
            Response.End();
        }
        protected void ReturnObj2(Object obj)
        {
            if (obj == null)
            {
                return;
            }
            string jsonStr = JsonConvert.SerializeObject(obj, Formatting.Indented, new JavaScriptDateTimeConverter());
            jsonStr = "{ 'success': 'true', 'data': " + jsonStr + "}";

            Response.Write(jsonStr);
            Response.End();
        }
        protected string RepairString(string dataStr)
        {
            string regex = @"[{]?\s*(?<FieldName>""\w*"":""""[,}])";
            MatchCollection matchs = Regex.Matches(dataStr, regex);
            foreach (Match match in matchs)
            {
                string empty = match.Groups["FieldName"].Value;
                if (empty.EndsWith("}"))
                {

                    empty = empty.Substring(0, empty.Length - 1);
                    string temp = "," + empty + "}";
                    if (dataStr.IndexOf(temp) >= 0)
                        empty = "," + empty;
                }
                dataStr = dataStr.Replace(empty, "");
            }
            return dataStr;//.Replace("Id\":\"\"", "Id\":0");
        }

        protected void ReturnSuccessMessage(string message)
        {
            Response.Clear();
            Response.Write("{'success':'true','message':'" + message + "'}");
            Response.End();

        }

        protected void ReturnSuccessMessage(string message, int id)
        {
            Response.Clear();
            Response.Write("{'success':'true','message':'" + message + "','Id':'" + id + "'}");
            Response.End();

        }

        protected void ReturnErrorMessage(string message)
        {
            Response.Clear();
            Response.Write("{'success':'false','message':'" + message.Replace("\r\n", "").Replace("'", "") + "'}");
            Response.End();
        }

        protected void ReturnList(int totalRecords, Object objects)
        {
            //StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
            //JsonSerializer jsonSerializer = new JsonSerializer();
            //jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //using (JsonWriter jsonWriter = new JsonTextWriter(sw))
            //{
            //    jsonWriter.Formatting = Formatting.Indented;
            //    jsonSerializer.Serialize(jsonWriter, objects);
            //}
            //string jsonStrs = "{'totalCount':'" + totalRecords.ToString() + "','topics':" + sw.ToString() + "}";

            string jsonStrs = JsonConvert.SerializeObject(objects);
            jsonStrs = "{'totalCount':'" + totalRecords.ToString() + "','topics':" + jsonStrs.ToString() + "}";
            
            Response.Write(jsonStrs);
            Response.End();
        }

        protected void ReturnList(int currtotalRecords, int totalRecords, Object objects)
        {
            string jsonStrs = JsonConvert.SerializeObject(objects);
            jsonStrs = "{'currtotalCount':'" + currtotalRecords.ToString() + "','totalCount':'" + totalRecords.ToString() + "','topics':" + jsonStrs + "}";
            Response.Write(jsonStrs);
            Response.End();
        }

        private Socket client = null;
        protected void SendMessage(string commandStr)
        {
            try
            {
                string socketIp = ConfigurationManager.AppSettings["SocketIP"].ToString();
                string socketPort = ConfigurationManager.AppSettings["SocketPort"].ToString();
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(socketIp), int.Parse(socketPort));
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(ipe);
                if (!client.Connected)
                    throw new Exception("连接失败!");
                //string data = PoliceId;
                string DataStr = "*YX" + commandStr;
                if (!string.IsNullOrEmpty(DataStr))
                {

                    byte[] data1 = Encoding.GetEncoding("GB2312").GetBytes(DataStr);
                    client.Send(data1, data1.Length, SocketFlags.None);
                    disposeSocket(client);
                }
            }
            catch (Exception ex)
            {

            }
        }
        // Methods
        public void disposeSocket(Socket socket)
        {
            if (!socket.Connected)
            {
                //ReturnSuccessMessage("发送消息成功");
            }
            else
            {
                socket.Close();
                this.disposeSocket(socket);
            }
        }

        public static string AppUrl
        {
            get
            {
                Uri uri = System.Web.HttpContext.Current.Request.Url;
                return "http://" + uri.Host.ToString() + (!string.IsNullOrEmpty(uri.Port.ToString()) ? (":" + uri.Port.ToString()) : "") + AppSiteName;
            }
        }

        public static string AppSiteName
        {
            get
            {
                string SiteAddress = "";
                SiteAddress = System.Web.HttpContext.Current.Request.ApplicationPath.ToString();
                if (System.Web.HttpContext.Current.Request.ApplicationPath.ToString() == "/")
                {
                    SiteAddress = "";
                }
                else
                {
                    SiteAddress = System.Web.HttpContext.Current.Request.ApplicationPath.ToString();
                }
                return SiteAddress.ToString();
            }
        }

        public  IEmployee LoginEmployee
        {
            get { return (Session["User"] as Employee); }
            set { Session["User"] = value; }
        }      
        /// <summary>
        /// 操作类型，比如新增、修改、删除、列表等
        /// </summary>
        protected string Action
        {
            get
            {
                return Request["action"];
            }
        }
        /// <summary>
        /// JSON格式提交的form数据
        /// </summary>
        protected string Data
        {
            get
            {
                return Request["data"];
            }
        }

        protected int SelfPage
        {
            get
            {
                int start;
                if (!int.TryParse(Request["start"], out start))
                {
                    start = 0;
                }
                //int start = int.Parse(Request["start"]);
                return start / PageSize + 1;
            }
        }

        protected int PageSize
        {
            get
            {
                int pageSzie;
                if (!int.TryParse(Request["limit"], out pageSzie))
                {
                    pageSzie = int.MaxValue;
                }
                return pageSzie;
            }
        }

        protected int Id
        {
            get
            {
                int id;
                if (!int.TryParse(Request["id"], out id))
                {
                    id = 0;
                }
                return id;
            }
        }

        protected int GetId()
        {
            return Id;
        }
        protected string GetPersonType()
        {
            return Request["type"];
        }
        protected string GetLoginPoliceName()
        {
            return LoginEmployee.Name;
        }
        protected string GetLoginPoliceCode()
        {
            return LoginEmployee.Code;
        }
        protected string GetCreatePoliceCode()
        {
            return Request["createPoliceCode"];
        }
    }
}